<template>
  <div class="login-page">
    <el-row>
      <el-col :span="12" class="aside">
        <div class="aside-inner">
          <router-link to="/">
            <img alt="汉德低代码平台" src="../assets/hdweb-log.png" class="logo-img" />
          </router-link>
          <h2>这是我用过的最好的建站工具</h2>
          <span class="text-white-70">陈伯良, Hand-Hitech</span>
        </div>
      </el-col>

      <el-col :span="12" class="login-area">
        <el-form ref="loginForm" :model="form" :rules="rules" label-position="top">
          <h2>欢迎回来</h2>
          <p class="subTitle">使用手机号码和验证码登录到汉德低代码平台</p>
          <el-form-item label="手机号码" required prop="cellphone">
            <el-input v-model="form.cellphone" placeholder="手机号码" :prefix-icon="User">
              <!-- <template v-slot:prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template> -->
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" required prop="verifyCode">
            <el-input v-model="form.verifyCode" placeholder="四位验证码" :prefix-icon="Lock">
              <!-- <template v-slot:prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template> -->
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button :loading="isLoginLoading" type="primary" size="large" @click="login">登录</el-button>
            <el-button size="large" :style="{ marginLeft: '20px' }" :disabled="codeButtonDisable" @click="getCode">
              {{ counter === 60 ? '获取验证码' : `${counter}秒后重发` }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { User, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useGlobalStore } from '@/stores/global'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { request } from '@/service/request'

const router = useRouter()
const userStore = useUserStore()
const globalStore = useGlobalStore()
const isLoginLoading = computed(() => globalStore.isOpLoading('login'))
const loginForm = ref<FormInstance>()
const counter = ref(60)
const codeButtonDisable = computed(() => {
  const reg = /^1[3-9]\d{9}$/
  return !reg.test(form.cellphone.trim()) || counter.value < 60
})

watch(counter, newValue => {
  if (newValue === 0) {
    clearInterval(timer)
    counter.value = 60
  }
})

const form = reactive({
  cellphone: '13040804447',
  verifyCode: ''
})

const cellphoneValidator = (rule: any, value: any) => {
  return new Promise<void>((resolve, reject) => {
    const reg = /^1[3-9]\d{9}$/
    const passed = reg.test(value.trim())
    if (passed) {
      resolve()
    } else {
      reject('手机号码格式不正确')
    }
  })
}

const rules = reactive<FormRules>({
  cellphone: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    // { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
    { asyncValidator: cellphoneValidator, trigger: 'blur' }
  ],
  verifyCode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
})

const login = () => {
  loginForm.value.validate().then(() => {
    const payload = {
      phoneNumber: form.cellphone,
      veriCode: form.verifyCode
    }
    userStore.loginAndFetch(payload).then(() => {
      ElMessage.success('登录成功 2秒后跳转首页')
      setTimeout(() => {
        router.push('/')
      }, 2000)
    })
  })
}

let timer = null
const startCounter = () => {
  counter.value--
  timer = setInterval(() => {
    counter.value--
  }, 1000)
}

const getCode = async () => {
  const rawData = await request<{ verifyCode: string }>('/users/genVeriCode', 'post', {
    phoneNumber: form.cellphone,
    isRemoteTest: true
  })
  ElMessage.success('验证码已发送，请注意查收')
  form.verifyCode = rawData.data.verifyCode
  startCounter()
}
</script>
<style lang="scss" scoped>
.logo-area {
  position: absolute;
  top: 30px;
  width: 150px;
}
.aside {
  height: 100vh;
  background-color: #1a1919;
  background-size: cover;
  background-repeat: no-repeat;
}
.aside .logo-img {
  width: 200px;
  margin-bottom: 20px;
}
.aside h2 {
  color: #cccccc;
  font-size: 29px;
}
.aside-inner {
  width: 60%;
  text-align: center;
}
.login-area {
  height: 100vh;
}
// .login-area .el-form {
//   width: 350px;
// }
.text-white-70 {
  color: #999;
  display: block;
  font-size: 19px;
}
.aside,
.login-area {
  display: flex !important;
  align-items: center;
  justify-content: center;
}
.login-area h2 {
  color: #333333;
  font-size: 29px;
  margin-bottom: 10px;
}
.login-area .subTitle {
  color: #666666;
  font-size: 18px;
  margin-bottom: 16px;
}
.login-area .el-form-item__label {
  display: none;
}
.login-area .el-input--prefix {
  left: auto;
  right: 30px;
  font-size: 19px;
}
.login-area .el-input {
  font-size: 17px;
  padding: 0px 0px 10px 30px;
}
</style>
